
'use strict';

const createConfig = require('uni-config-center');

const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const db = uniCloud.database();
const dbcmd = db.command;
const wxapi_token_id = 'wmzmall-wxapi-token';

const utils = require('../utils');

module.exports = {
	appid: uidConfig.config('h5-weixin.oauth.weixin.appid'),
	token: '',
	token_expired: 0,
	get_token: async function() {
		let res = await db.collection('wmzmall-token').doc(wxapi_token_id).get();
		const [wxToken] = res.data;
		if (wxToken && wxToken._id && wxToken.token_expired > Date.now()) {
			this.token = wxToken.token;
			this.token_expired = wxToken.token_expired;
			return this.token;
		}
		
		const url = uidConfig.config('agent.wxapi-token');
		
		if (!url) {
			throw new Error('wxapi-token 请求地址不存在');
		}
		
		// 请求 wxapi token
		res = await utils.http.get(url);
		
		console.log('utils.http.get res', res);
		
		if (res.code !== 200) {
			throw new Error('wxapi-token 获取失败');
		}
		
		this.token = res.datas.access_token;
		this.token_expired = res.datas.expires_time;
		
		// 写入最新 token 数据
		await db.collection('wmzmall-token').doc(wxapi_token_id).set({
			token: this.token,
			token_expired: this.token_expired,
			res: res,
			req: {},
			type: 'wxapi'
		});
		
		return this.token;
	}
}
